package com.boarsoft.boar.message.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.message.biz.RecipientQueueBiz;
import com.boarsoft.boar.message.biz.TargetQueueBiz;
import com.boarsoft.boar.message.entity.RecipientQueueEntity;
import com.boarsoft.boar.message.entity.TargetQueueEntity;
import com.boarsoft.boar.message.flow.MessageStr;
import com.boarsoft.boar.message.service.MsgServerService;
import com.boarsoft.message.bean.MessageEntity;
import com.boarsoft.message.bean.MessageQueryParam;
import com.boarsoft.message.bean.TargetQueueInfo;
import com.boarsoft.message.broker.MessageBroker;
import com.boarsoft.rpc.bean.RpcReferenceConfig;
import com.boarsoft.rpc.bean.RpcRegistry;
import com.boarsoft.rpc.core.RpcContext;

/**
 * 此类通过调用远程message-server的broker接口提供队列的动态添加、删除、查询和监控
 * 
 * @author Mac_J
 *
 */
@Component("msgServerSvc")
public class MsgServerServiceImpl implements MsgServerService {
	private static final Logger log = LoggerFactory.getLogger(MsgServerServiceImpl.class);

	@Autowired
	@Qualifier("msgBroker")
	private MessageBroker broker;

	@Autowired
	private RpcContext rpcContext;
	
	@Autowired
	protected TargetQueueBiz targetQueueBiz;
	@Autowired
	protected RecipientQueueBiz recipientQueueBiz;
	
	@Override
	public List<TargetQueueEntity> getTargetQueues() {
		return targetQueueBiz.list();
	}

	@Override
	public List<RecipientQueueEntity> getRecipientsQueues() {
		return recipientQueueBiz.list();
	}

	@Override
	public List<TargetQueueInfo> getQueueInfo(String addr) {
		List<TargetQueueInfo> lt = new ArrayList<>();
		if (broker == null) {
			return lt;
		}
		// 指定rpc地址
		RpcContext.specify2(addr);
		try {
			Map<String, TargetQueueInfo> tqMap = broker.getTargetQueue();
			for (Entry<String, TargetQueueInfo> en : tqMap.entrySet()) {
				TargetQueueInfo tq = en.getValue();
				if (tq == null) {
					log.warn("Message broker return null");
				} else {
					lt.add(tq);
				}
			}
			return lt;
		} finally {
			// 重置rpc地址
			RpcContext.specify2(null);
		}
	}

	@Override
	public List<MessageEntity> list(String target, String addr, String messageId, Date startTime, Date endTime,
			Short status, String key, int pageNo, int pageSize) {
		RpcContext.specify2(addr);
		try {
			MessageQueryParam param = new MessageQueryParam();
			param.setId(messageId);
			param.setKey(key);
			param.setEndTime(endTime);
			param.setStartTime(startTime);
			param.setStatus(status);
			param.setPageNo(pageNo);
			param.setPageSize(pageSize);
			return broker.query(target, param);
		} catch (Exception e) {
			log.error("query message error:", e);
			return null;
		} finally {
			RpcContext.specify2(null);
		}
	}

	@Override
	public List<Map<String, Object>> count(String target, Date startTime, Date endTime) {
		return new ArrayList<Map<String, Object>>();
		// try {
		// List<Map<String, Object>> addrs = list();
		// MessageQueryParam param = new MessageQueryParam();
		// param.setStartTime(startTime);
		// param.setEndTime(endTime);
		// List<List<Map<String, Object>>> sumList = new ArrayList<>();
		// // 查看每个库该队列消息总数
		// for (Map<String, Object> map : addrs) {
		// String addr = map.get("addr").toString();
		// RpcContext.specify2(addr);
		// list = broker.count(target, param);
		// sumList.add(list);
		// }
		//
		// // 将每个库的消息再次汇总
		// int sum = 0;
		// List<Map<String, Object>> countList = new ArrayList<>();
		// for (List<Map<String, Object>> list : sumList) {
		// for (Map<String, Object> subMap : list) {
		// Object status = subMap.get("tStatus");
		// Integer count = (Integer) subMap.get("count");
		// // 如果链表中存在该状态消息数据则累加，否则新增
		// if (checkMap(countList, status)) {
		// setVal(countList, status, count);
		// } else {
		// Map<String, Object> map = new HashMap<>();
		// map.put("count", count);
		// map.put("tStatus", status);
		// countList.add(map);
		// }
		// // 累计消息总数
		// sum += count;
		// }
		// }
		// Map<String, Object> totalMap = new HashMap<>();
		// totalMap.put("count", sum);
		// totalMap.put("tStatus", "all");
		// countList.add(totalMap);
		//
		// return countList;
		// } catch (Exception e) {
		// log.error("count message error:", e);
		// return null;
		// } finally {
		// RpcContext.specify2(null);
		// }
	}

//	private void setVal(List<Map<String, Object>> list, Object status, Integer count) {
//		for (Map<String, Object> map : list) {
//			if (map.get("tStatus") != null && status.equals(map.get("tStatus"))) {
//				map.put("count", (Integer) map.get("count") + count);
//				break;
//			}
//		}
//	}
//
//	private boolean checkMap(List<Map<String, Object>> list, Object status) {
//		for (Map<String, Object> map : list) {
//			if (map.get("tStatus") != null && status.equals(map.get("tStatus"))) {
//				return true;
//			}
//		}
//		return false;
//	}

	@Override
	public List<Map<String, Object>> list() {
		RpcRegistry reg = rpcContext.getMyRegistry();
		Map<String, RpcReferenceConfig> refMap = reg.getReferenceMap();
		RpcReferenceConfig rc = refMap.get("serverMsgSvc");
		List<RpcRegistry> aLt = rpcContext.getAllProvidersByKey(rc.getSign(), false);
		List<Map<String, Object>> rLt = new ArrayList<Map<String, Object>>();
		// 当没有活动的消息中心时，aLt可能为空
		if (aLt != null && !aLt.isEmpty()) {
			for (RpcRegistry rr : aLt) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put(MessageStr.ADDR, rr.getKey());
				rLt.add(map);
			}
		}
		return rLt;
	}

	@Override
	public boolean test() {
		return true;
	}
}